package com.amose.consumer.controller;

import com.amose.consumer.UserFeignClientUse;
import com.amose.serviceapi.User;
import com.amose.serviceapi.UserFeignClient;
import com.netflix.appinfo.InstanceInfo;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * @author yangpeng
 * @time 2020/11/3
 * @since 1.0.0
 */
@RestController
@RequestMapping("/consume")
public class ConsumerController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private UserFeignClientUse userFeignClientUse;


    @GetMapping("/hello")
    public String sayHelloWithProvider(){
        //1. 从eureka注册中心获取服务提供者的服务实例信息
        List<ServiceInstance> serviceprovider = discoveryClient.getInstances("SERVICEPROVIDER");
        //2.选择使用一个
        ServiceInstance instanceInfo = serviceprovider.get(0);
        //调用远程接口
        // 服务提供者标准元数据信息 :主机名，服务名，ip地址，端口号等信息，这些信息会被发布到服务注册表中
        String host = instanceInfo.getHost();
        int port = instanceInfo.getPort();
        //服务提供者自定义元数据信息，也会被发布到服务注册表中
        Map<String, String> metadata = instanceInfo.getMetadata();
        String url = "http://"+host+":"+port+"/provider/hello";
        System.out.println("=========从eureka中获取到服务提供者的url:"+url);
        return restTemplate.getForObject(url, String.class);
    }

    @GetMapping("/hello2")
    public String sayHelloWithProvider2(){

        String url = "http://ServiceProvider/provider/hello";
        return restTemplate.getForObject(url, String.class);
    }

    @GetMapping("/hello3")
    public User sayHelloWithProvider3(){
        return userFeignClientUse.getById(1L);
    }
}
